import { createApp } from "vue";
import App from "./App.vue";
import Antd, { message } from "ant-design-vue";
import "ant-design-vue/dist/antd.css";
import * as antdIcons from "@ant-design/icons-vue";
import router from "./router";
import { createPinia } from "pinia";
import axios from "axios";

const app = createApp(App);

// 开发环境则引入mockjs
require("./mock/index.js");

axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
// 添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
  (config) => {
    const token = sessionStorage.getItem("Authorization");
    if (token) {
      config.headers.Authorization = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 添加返回拦截器，判断是否401
axios.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response) {
      const { status, data } = error.response;
      switch (status) {
        case 401:
          // 服务器端返回401，说明Token已无效
          sessionStorage.removeItem("Authorization");
          router.replace({
            path: "/login",
            query: {
              redirect: router.currentRoute.fullPath,
            },
          });
          break;
      }

      if (data && data.Message) {
        message.error(data.Message);
      }
      return Promise.reject(data);
    }
  }
);
app.config.globalProperties.$axios = axios;

Object.keys(antdIcons).forEach((key) => {
  app.component(key, antdIcons[key]);
});
app.config.globalProperties.$antdIcons = antdIcons;

app.use(Antd).use(router).use(createPinia()).mount("#app");
